<template>
  <div class="Palying" id="play" ref="Palying" :style="{backgroundColor: TenColorStyle.backgroundColor}">
    <transition
      name="fademode">
      <div class="head" v-if="show_red && showlay" >
        <Hread :text="'早起专属优惠，加入会员双倍返现，使用红包'" :Styles="headColor" @show="showPopup"></Hread>
      </div>
    </transition>
    <div class="content" @touchstart="PageStart" @touchmove="PageMove" @touchend="PageEnd">
      <div class="title" @click="isfooer=!isfooer" :style="{color:TenColorStyle.borderColor}">第{{chapter.chapter_no}}节 |
        {{chapter.chapter_name}}
      </div>
      <div class="body" ref="lrcBox" @click="AnswerPopuphide">
        <p v-for=" (a,i) in Chapter" v-html="a.text"
           :class="{'active': i === curLrcIndex,'font':a.time!=='','col':a.time===''}"
           :style="{ 'font-size': fontSize+'px',lineHeight:(fontSize*2)+'px',color:TenColorStyle.borderColor}"
           @click="_lrcbtn(a.time,i)"
        ></p>
      </div>
      <div class="btn">
        <div class="popupst" v-if="AnswerPopupshow">
          <div class="conten">
            <div class="text">
              点此去做题，完成当日题目才能完成阅读任务
              <span></span>
            </div>
          </div>
        </div>
        <p v-if="!isBtns"
           :style="{color:TenColorStyle.mode===1?'#999999':(TenColorStyle.mode===2?'#c1c1c2':'#333333')}"><i
          class="iconfont icon-daojishi"></i>倒计时结束后，即可进入答题</p>
        <Btn :obj='btnstyle' :text="textbtn" :dis="dis" v-on:statr="goAnswer()"></Btn>
      </div>
    </div>
    <toast v-if="show_red && !showlay"  :red_count="red_count" :red_desc="red_desc" @hide="hidetoast" @buyVip="showPopup"></toast>
    <transition
      name="bouncespeed">
      <Fontsize v-if="PopupFontsize" :TenFontSizi="TenFontSizi" :Styles="TenColorStyle"
                @TenFontSizi="OptiveTenFontSizi"></Fontsize>
    </transition>
    <transition
      name="bouncespeed">
      <Background v-if="PopupBackground" :Styles="TenColorStyle" @Color="OptiveColor"></Background>
    </transition>
    <transition
      name="bounceshade">
      <div class="shade" v-show="shade" @click="hideall"></div>
    </transition>
    <transition
      name="bouncespeed">
      <Speed v-if="PopupSpeed" @hide="Speedhide" @Speed="Speed" :speeds="$refs.PalyFooter.speed"
             :Styles="TenColorStyle"></Speed>
    </transition>
    <transition
      name="bounce">
      <PalyFooter v-show="isfooer" @SpeedShow="SpeedShow" @fontsizeShow="FontsizeShow" @backgroundShow="BacgroundShow"
                  @lrBox="lrBox" @Modifyshow="PopupShow" :Styles="TenColorStyle "
                  ref="PalyFooter" :chapter_url="items.chapter.chapter_voice_url"></PalyFooter>
    </transition>
    <transition
      name="bounceshade">
      <div class="shade" style="z-index: 400;background: rgba(0, 0, 0, 0.8);" v-show="shade2" @click="hideall"></div>
    </transition>
    <transition
      name="bouncepop">

      <div v-if="Popup">
        <Popup @hide="Popuphide"></Popup>
      </div>
    </transition>
  </div>
</template>

<script>
  import 'animate.css'
  import Hread from './components/Head/index'
  import PalyFooter from './components/Footer/index'
  import Fontsize from './components/Fontsize/index'
  import Background from './components/Background/index'
  import Speed from './components/Speed/index'
  import Popup from './components/Popup/index'
  import Btn from '../../components/btn/index'
  import toast from './components/toes/index'
  import $ from 'jquery'

  export default {
    name: "index",
    data: function () {
      var TenFontSizi = localStorage.getItem('TenFontSizi') ? JSON.parse(localStorage.getItem('TenFontSizi')) : {
        fontSize: 18,
        fontSizeval: 25
      }
      var TenColorStyle = localStorage.getItem('TenColorStyle') ? JSON.parse(localStorage.getItem('TenColorStyle')) : {
        mode: 1,
      }
      var btnStyle = localStorage.getItem('TenColorStyle') ? JSON.parse(localStorage.getItem('TenColorStyle')).btnStyle ? JSON.parse(localStorage.getItem('TenColorStyle')).btnStyle : {
        backgroundColor: '#f2f2f2',
        width: '85%',
        height: '4.5rem',
        color: '#333',
        opacity: 1,
        boxShadow: '0 10px 24px 0 rgba(255, 208, 0, 0.4)'
      } : {
        backgroundColor: '#f2f2f2',
        width: '85%',
        height: '4.5rem',
        color: '#333',
        opacity: 1,
        boxShadow: '0 10px 24px 0 rgba(255, 208, 0, 0.4)'
      }
      return {
        // 是否展示红包组件
        show_red:false,
        red_desc:'',
        shade: false,
        shade2: false,
        headColor:{
          backgroundColor:'#fff5f5',
          color:'#ff5059'
        },
        TenFontSizi: TenFontSizi,
        TenColorStyle: TenColorStyle,
        curLrcIndex: 0,
        PopupSpeed: false,
        PopupModify: false,
        PopupFontsize: false,
        PopupBackground: false,
        WordItems: {},
        Popup: false,
        fontSize: TenFontSizi.fontSize,
        isRecord: true,
        btnstyle: btnStyle,
        textbtn: '读完去做题(05:00)',
        dis: false,
        translateY: 0,
        Time: 5,
        bgcolor: {
          Y: -1,
          X: -1,
          Color: '#ffd000'
        },
        isBtns: false,
        isTouch: true,
        isfooer: true,
        isplay: false,
        Timeout: null,
        timer: null,
        Playheight: '',
        scroll: '',
        // 是否展示横幅，与弹窗互斥
        showlay: false,
        AnswerPopupshow: false
      }
    },
    props: ['chapter', 'items', 'isListen','cur_day','red_count'],
    computed: {
      Chapter: {
        get: function () {
          this.items.chapter.chapter_text = this.$Mate.qingReadTextRetuen(this.items.chapter.chapter_text)
          this.items.chapter.chapter_handout_text = this.$Mate.qingReadTextRetuen(this.items.chapter.chapter_handout_text)
          this.items.chapter.chapter_text = this.$Mate.fetch(this.items.chapter.chapter_text)
          return this.items.chapter.chapter_text
        },
        set: function (v) {
          this.obj.opacity = v
        }
      }
    },
    mounted: function () {
      // var readsw = localStorage.getItem('readseewes')
      // if (this.$Login.Vip_token.reading_vip_state === 1 && !readsw && readsw !== 1) {
      //   this.AnswerPopupshow = true
      // }
      if (this.$Login.Vip_token.reading_vip_state ===0) {
        // 试听设置倒计时
        this.SetTime(0)
        // 判断开启红包以及统计次数
        let current_activity_start_time = window.localStorage.getItem("current_activity_start_time")
        let current_activity_current_time = window.localStorage.getItem("current_activity_current_time")
        if(current_activity_start_time && parseInt(current_activity_start_time) !== -1){
          if(this.$Login.Vip_token.reading_vip_state ===0 && this.red_count){
            this.judgeCount(current_activity_start_time,current_activity_current_time)
          }
        }

      } else {
        if(window.localStorage.getItem('tenChapterDate')!== this.cur_day){
          // 存放要移除元素的key
          let remove_flag = []
          // 清除关于倒计时的缓存
          for(let i=0;i<window.localStorage.length;i++){
            remove_flag.push(window.localStorage.key(i))
          }
          for(let remove_key of remove_flag){
            if(remove_key.indexOf('tenChapter')!==-1){
              window.localStorage.removeItem(remove_key)
            }
          }
        }
        // 1.判断是否是当天，如果不是，则更新记录时间，并且重置倒计时时间(localhost)
        if(!window.localStorage.getItem('tenChapterDate') || !window.localStorage.getItem('tenChapterTime' + this.items.chapter.chapter_id)){
          window.localStorage.setItem('tenChapterDate',this.cur_day)
          window.localStorage.setItem('tenChapterTime'+ this.items.chapter.chapter_id,this.items.delay_timestamp / 1000)
        }
        this.SetTime(window.localStorage.getItem('tenChapterTime'+ this.items.chapter.chapter_id))
      }
    },
    destroyed: function () {
      window.clearInterval(this.timer)
    },
    methods: {
      Modifyshow: function () {
        this.isfooer = false
        this.shade = true
      },
      Modifyhide: function () {
        this.isfooer = true
      },
      SpeedShow: function () {
        this.isfooer = false
        this.shade = true
        this.PopupSpeed = true
      },
      FontsizeShow: function () {
        this.isfooer = false
        this.shade = true
        this.PopupFontsize = true
      },
      BacgroundShow: function () {
        this.isfooer = false
        this.shade = true
        this.PopupBackground = true
      },
      Speedhide: function () {
        this.isfooer = true
        this.shade = false
        this.PopupSpeed = false
      },
      Speed: function (str) {
        this.$refs.PalyFooter.Speed(str)
      },
      lrBox: function (Time) {
        this.Chapter.forEach(function (item, index) {
          if (item.time.indexOf(Time.substr(0, 6)) === 0) {
            this.curLrcIndex = index
            var lrBox = this.$refs.lrcBox.childNodes
            // var offsetHeight = lrBox[index].offsetHeight
            // var body = document.body.clientHeight
            this.translateY = lrBox[index].offsetTop - 50
            if (this.isTouch) {
              $('html,body').animate({
                scrollTop: this.translateY
              }, 1000)
              // document.getElementById('play').scrollTop = this.translateY
            }
          }
        }.bind(this))
      },
      _lrcbtn: function (tims, i) {
        this.isfooer = true
        let audio = this.$refs.audio
        var Time = tims.split(':')
        if (tims === '') {
          return
        }
        if (parseInt(Time[0]) === 0) {
          audio.currentTime = parseInt(Time[1])
        } else {
          audio.currentTime = (parseInt(Time[0]) * 60) + parseInt(Time[1])
        }
        this.Plays(i)
      },
      hideall: function () {
        setTimeout(() => {
          this.isfooer = true
        }, 300)
        this.shade = false
        this.PopupModify = false
        this.PopupSpeed = false
        this.PopupFontsize = false
        this.PopupBackground = false
      },
      Click: function (obj) {
        this.isfooer = true
        this.Wordhide()
        if (obj.Time === '') {
          return
        }
        var Time = obj.Time.split(':')
        if (parseInt(Time[0]) === 0) {
          this.$refs.PalyFooter.$refs.audio.currentTime = parseInt(Time[1])
        } else {
          this.$refs.PalyFooter.$refs.audio.currentTime = (parseInt(Time[0]) * 60) + parseInt(Time[1])
        }
        this.$refs.PalyFooter.$refs.audio.play()
        var lrBox = this.$refs.lrcBox.childNodes
        $('html,body').animate({
          scrollTop: lrBox[obj.i].offsetTop - 50
        }, 500)
        // this.lrBox(obj.Time)
      },
      PageStart: function (e) {
        clearTimeout(this.Timeout)
        this.$Mate.PageStart(e)
        this.isTouch = false
      },
      PageMove: function (e) {
        clearTimeout(this.Timeout)
        this.isTouch = false
        this.$Mate.PageMove(e, res => {
          // if (res.direction === 'y') {
          //   this.isfooer = res.is
          // }
          // if (res.direction === 'x' && res.is) {
          //   this.go('/Handouts')
          // }
        })
      },
      PageEnd: function (e) {
        var _this = this
        this.$Mate.PageEnd(e, res => {
          if (res.direction === 'y') {
            this.isfooer = res.is
          }
        })
        if (this.PopupWord) {
          this.Wordhide();
        }
        this.Timeout = setTimeout(() => {
          _this.isTouch = true
        }, 3000)
      },
      OptiveColor: function (obj) {
        var _this = this
        this.TenColorStyle = obj
        // 如果有倒计时不进行颜色更换
        if (window.localStorage.getItem('tenChapterTime' + this.items.chapter.chapter_id) !== '0') {
          _this.btnstyle = {
            backgroundColor: obj.mode === 1 ? '#f2f2f2' : (obj.mode === 2 ? '#505055' : '#eee7d9'),
            width: '85%',
            height: '4.5rem',
            color: obj.mode === 1 ? '#333333' : (obj.mode === 2 ? '#ffffff' : '#333333'),
            opacity: 1,
            // boxShadow: '0 10px 24px 0 rgba(255, 208, 0, 0.4)'
          }
        } else {
          if (obj.btnStyle) {
            _this.btnstyle = obj.btnStyle
          } else {
            _this.btnstyle = {
              backgroundColor: obj.mode === 1 ? '#ffd000' : (obj.mode === 2 ? '#ffffff' : '#66440a'),
              width: '85%',
              height: '4.5rem',
              color: obj.mode === 1 ? '#66440a' : (obj.mode === 2 ? '#ffffff' : '#333333'),
              opacity: 1,
              boxShadow: obj.mode === 1 ? '0 10px 24px 0 rgba(255, 208, 0, 0.4)' : 'none'
            }
          }
          localStorage.setItem('TenColorStyle', JSON.stringify(obj))
        }

      },
      OptiveTenFontSizi: function (obj) {
        this.TenFontSizi = obj
        localStorage.setItem('TenFontSizi', JSON.stringify(obj))
        this.fontSize = obj.fontSize
      },
      Popuphide: function () {
        this.Popup = false
        this.shade2 = false
      },
      PopupShow: function () {
        this.Popup = true
        this.shade2 = true
      },
      goAnswer: function () {
        if (this.isListen === 1) {
          // 试听
          this.$router.push({
            name: 'BuyVip',
            query: {
              share_id: this.$route.query.share_id,
              share_token: this.$route.query.share_token,
              goods_id: this.$route.query.goods_id
            }
          })
        } else {
          this.$router.push({
            name: 'Answer',
            query: {
              user_read_book_record_id: this.items.user_read_book_record_id,
              user_chapter_read_record_id: this.items.user_chapter_read_record_id,
              testpaper_id: this.chapter.testpaper_id
            }
          })
        }

      },
      SetTime: function (S) {
        var _this = this
        if (S === 0) {
          _this.btnstyle = {
            backgroundColor: _this.TenColorStyle.mode === 1 ? '#ffd000' : (_this.TenColorStyle.mode === 2 ? '#ffffff' : '#66440a'),
            width: '85%',
            height: '4.5rem',
            color: _this.TenColorStyle.mode === 1 ? '#66440a' : (_this.TenColorStyle.mode === 2 ? '#333333' : '#ffffff'),
            opacity: 1,
            boxShadow: _this.TenColorStyle.mode === 1 ? '0 10px 24px 0 rgba(255, 208, 0, 0.4)' : (_this.TenColorStyle.mode === 2 ? 'none' : '0 10px 24px 0 rgba(102, 68, 10, 0.3);')
          }
          _this.isBtns = true
          _this.dis = false
          if (this.isListen === 1) {
            // 试听
            _this.textbtn = '加入会员'
          } else {
            _this.textbtn = '读完去做题'
          }

        } else {
          var t = S
          var m = 0
          var s = 0
          m = Math.floor(t / 60 % 60)
          m < 10 && (m = '0' + m)
          s = Math.floor(t % 60)

          function countDown() {
            s--
            window.localStorage.setItem('tenChapterTime' + _this.items.chapter.chapter_id, t--, 24)
            s < 10 && (s = '0' + s)
            if (s.length >= 3) {
              s = 59
              m = "0" + (Number(m) - 1)
            }
            if (m.length >= 3) {
              m = '00'
              s = '00'
              _this.btnstyle = {
                backgroundColor: _this.TenColorStyle.mode === 1 ? '#ffd000' : (_this.TenColorStyle.mode === 2 ? '#ffffff' : '#66440a'),
                width: '85%',
                height: '4.5rem',
                color: _this.TenColorStyle.mode === 1 ? '#66440a' : (_this.TenColorStyle.mode === 2 ? '#333333' : '#ffffff'),
                opacity: 1,
                boxShadow: _this.TenColorStyle.mode === 1 ? '0 10px 24px 0 rgba(255, 208, 0, 0.4)' : (_this.TenColorStyle.mode === 2 ? 'none' : '0 10px 24px 0 rgba(102, 68, 10, 0.3);')
              }
              _this.isBtns = true
              _this.dis = false
              _this.textbtn = '读完去做题'
              window.clearInterval(_this.timer)
              return;
            }
            _this.isBtns = false
            _this.btnstyle = {
              backgroundColor: _this.TenColorStyle.mode === 1 ? '#f2f2f2' : (_this.TenColorStyle.mode === 2 ? '#505055' : '#eee7d9'),
              width: '85%',
              height: '4.5rem',
              color: _this.TenColorStyle.mode === 1 ? '#333333' : (_this.TenColorStyle.mode === 2 ? '#ffffff' : '#333333'),
              opacity: 1,
              // boxShadow: '0 10px 24px 0 rgba(255, 208, 0, 0.4)'
            }
            _this.textbtn = '读完去做题（' + m + ':' + s + '）'
            _this.dis = true
          }

          this.timer = window.setInterval(countDown, 1000)
        }
      },
      // 判断进入次数
      judgeCount:function(start_time,cur_time){
        start_time = parseInt(start_time)
        cur_time = parseInt(cur_time)
        let count =0
        // 是否是vip vip 不展示红包组件
        setTimeout(()=>{
          this.show_red = true
        },700)
          // 判断周期，若为新的一期则进行次数，时间初始化
          if(!window.localStorage.getItem('tenStartTime') || start_time !== parseInt(window.localStorage.getItem('tenStartTime'))){
            window.localStorage.setItem('tenRedCount',1)
            window.localStorage.setItem('tenStartTime',start_time)
            window.localStorage.setItem('tenCurTime',cur_time)
            this.red_desc = '恭喜你获得【早起计划】 限量红包'+this.red_count+'元'
            // 展示弹窗
            this.showlay = false
          }else{
            // 累计进入次数并判断是否进行当前时间，次数持久化(当前时间大于前次记录时间3天),并且只谈3次
            count = window.parseInt(window.localStorage.getItem('tenRedCount'))+1
            if((cur_time - parseInt(window.localStorage.getItem('tenCurTime'))) >=60*1000*60*24*3 && window.parseInt(window.localStorage.getItem('tenRedCount'))<3){
              window.localStorage.setItem('tenRedCount',count)
              window.localStorage.setItem('tenCurTime',cur_time)
              // 判断次数，如果为1，展示领取红包，如果非1，展示过期文案
              if(count !== 1) {
                this.red_desc = '您的红包即将过期 记得使用哦～'
              }
              // 展示弹窗
              this.showlay = false
            }else{
              // 若不需要持久化则默认不弹窗
              this.showlay =true
              if(parseInt(window.localStorage.getItem('tenRedCount')) === 1){
                this.red_desc = '恭喜你获得【早起计划】 限量红包'+this.red_count+'元'
              }else{
                this.red_desc = '您的红包即将过期 记得使用哦～'
              }
            }

          }

      },
      // 隐藏红包弹窗
      hidetoast: function () {
        this.showlay = true
      },
      // 显示红包弹窗
      showPopup:function () {
        // this.showlay = false
        // 跳转打卡页面
        this.$router.push({
          name:'BuyVip'
        })
      },
      AnswerPopuphide: function () {
        this.AnswerPopupshow = false
        localStorage.setItem('readseewes', 1)
      }
    },
    components: {Hread, PalyFooter, Fontsize, Speed, Popup, Btn, Background,toast}
  }
</script>

<style scoped>
  @import "./css/index.css";
</style>
